<?php
declare (strict_types = 1);

namespace app\tools;

use app\exception\LogicException;
use app\facade\CurlFacade;
use app\facade\StringFacade;
use Exception;
use Tencent\TLSSigAPIv2;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Trtc\V20190722\Models\DismissRoomByStrRoomIdRequest;
use TencentCloud\Trtc\V20190722\Models\DismissRoomRequest;
use TencentCloud\Trtc\V20190722\Models\RemoveUserByStrRoomIdRequest;
use TencentCloud\Trtc\V20190722\Models\RemoveUserRequest;
use TencentCloud\Trtc\V20190722\TrtcClient;
use think\App;
use think\facade\Log;

final class TrtcTool
{
    private $SecretId;
    private $SecretKey;
    private $endpoint;
    private $region;
    private $SdkAppid;

    // user sig key
    private $userSigKey;

    /**
     * WechatTool constructor.
     * @throws Exception
     */
    public function __construct()
    {
        $this->SecretId = config('trtc.secret_id');
        $this->SecretKey = config('trtc.secret_key');
        $this->endpoint = config('trtc.endpoint');
        $this->region = config('trtc.region');
        $this->SdkAppid = config('trtc.sdk_appid');

        // user sig key
        $this->userSigKey = config('trtc.user_sig_key');
    }

    /**
     * UserSig有效期默认一天
     *
     * @param $userId
     * @param int $expire
     * @return string
     * @throws LogicException
     */
    public function userSig($userId, $expire = 86400)
    {
        try {
            $api = new TLSSigAPIv2($this->SdkAppid, $this->userSigKey);
            return $api->genUserSig($userId, $expire);
        } catch (Exception $e) {
            Log::debug('TrtcUserSigException: file=' . $e->getFile() . ', line=' . $e->getLine() . ', message=' . $e->getMessage());
            throw new LogicException(lang('communal.trtc exception'));
        }
    }

    /**
     * 移除用户
     *
     * @param $roomId
     * @param $userIds
     * @return mixed
     * @throws LogicException
     */
    public function removeUserRequest($roomId, $userIds)
    {
        try {
            $cred = new Credential($this->SecretId, $this->SecretKey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint($this->endpoint);

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new TrtcClient($cred, $this->region, $clientProfile);

            $req = new RemoveUserRequest();

            $params = array(
                "SdkAppId" => (int)$this->SdkAppid,
                "RoomId" => (int)$roomId,
                "UserIds" => is_array($userIds) ? $userIds : [$userIds],
            );
            $req->fromJsonString(json_encode($params));
            $resp = $client->RemoveUser($req);
            return json_decode($resp->toJsonString(), true);
        } catch (TencentCloudSDKException $e) {
            Log::debug('TrtcRemoveUserRequestException: requestId=' . $e->getRequestId() . ', errorCode:=' . $e->getErrorCode() . ', message=' . $e->getMessage());
            throw new LogicException(lang('communal.trtc exception'));
        }
    }

    /**
     * 解散房间
     *
     * @param $roomId
     * @return mixed
     * @throws LogicException
     */
    public function dismissRoomRequest($roomId)
    {
        try {
            $cred = new Credential($this->SecretId, $this->SecretKey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint($this->endpoint);

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new TrtcClient($cred, $this->region, $clientProfile);

            $req = new DismissRoomRequest();

            $params = array(
                "SdkAppId" => (int)$this->SdkAppid,
                "RoomId" => (int)$roomId,
            );
            $req->fromJsonString(json_encode($params));
            $resp = $client->DismissRoom($req);
            return json_decode($resp->toJsonString(), true);
        } catch (TencentCloudSDKException $e) {
            Log::debug('TrtcDismissRoomRequestException: requestId=' . $e->getRequestId() . ', errorCode:=' . $e->getErrorCode() . ', message=' . $e->getMessage());
            throw new LogicException(lang('communal.trtc exception'));
        }
    }

    /**
     * 移出用户（字符串房间号）
     *
     * @param $roomId
     * @param $userIds
     * @return mixed
     * @throws LogicException
     */
    public function removeUserByStrRoomIdRequest($roomId, $userIds)
    {
        try {
            $cred = new Credential($this->SecretId, $this->SecretKey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint($this->endpoint);

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new TrtcClient($cred, $this->region, $clientProfile);

            $req = new RemoveUserByStrRoomIdRequest();

            $params = array(
                "SdkAppId" => (int)$this->SdkAppid,
                "RoomId" => (string)$roomId,
                "UserIds" => is_array($userIds) ? $userIds : [$userIds],
            );
            $req->fromJsonString(json_encode($params));
            $resp = $client->RemoveUserByStrRoomId($req);
            return json_decode($resp->toJsonString(), true);
        } catch (TencentCloudSDKException $e) {
            Log::debug('TrtcRemoveUserByStrRoomIdRequestException: requestId=' . $e->getRequestId() . ', errorCode:=' . $e->getErrorCode() . ', message=' . $e->getMessage());
            throw new LogicException(lang('communal.trtc exception'));
        }
    }

    /**
     * 解散房间（字符串房间号）
     *
     * @param $roomId
     * @return mixed
     * @throws LogicException
     */
    public function dismissRoomByStrRoomIdRequest($roomId)
    {
        try {
            $cred = new Credential($this->SecretId, $this->SecretKey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint($this->endpoint);

            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new TrtcClient($cred, $this->region, $clientProfile);

            $req = new DismissRoomByStrRoomIdRequest();

            $params = array(
                "SdkAppId" => (int)$this->SdkAppid,
                "RoomId" => (string)$roomId,
            );
            $req->fromJsonString(json_encode($params));
            $resp = $client->DismissRoomByStrRoomId($req);
            return json_decode($resp->toJsonString(), true);
        }
        catch(TencentCloudSDKException $e) {
            Log::debug('TrtcDismissRoomByStrRoomIdRequestException: requestId=' . $e->getRequestId() . ', errorCode:=' . $e->getErrorCode() . ', message=' . $e->getMessage());
            throw new LogicException(lang('communal.trtc exception'));
        }
    }
}
